{% extends "base.html" %}

{% block content %}
<div class="container-xl py-4">
    <h2 class="page-title">库存管理</h2>
    
    <!-- 搜索表单 -->
    <div class="card mb-4">
        <div class="card-body">
            <form id="searchForm" class="row g-3">
                <div class="col-md-3">
                    <label for="manufacturer" class="form-label">生产厂商</label>
                    <select class="form-select" id="manufacturer" name="manufacturer">
                        <option value="">全部</option>
                        {% for m in manufacturers %}
                        <option value="{{ m }}">{{ m }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div class="col-md-3">
                    <label for="type" class="form-label">设备类型</label>
                    <select class="form-select" id="type" name="type">
                        <option value="">全部</option>
                        {% for t in types %}
                        <option value="{{ t }}">{{ t }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div class="col-md-3">
                    <label for="standard" class="form-label">制式</label>
                    <select class="form-select" id="standard" name="standard">
                        <option value="">全部</option>
                        {% for s in standards %}
                        <option value="{{ s }}">{{ s }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div class="col-md-3 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary me-2">搜索</button>
                    <button type="button" class="btn btn-success" id="exportBtn">导出CSV</button>
                    <button type="button" class="btn btn-danger ms-2" id="deleteBtn">删除选中</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 设备列表 -->
    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <th><input type="checkbox" id="selectAll"></th>
                            <th>SN码</th>
                            <th>生产厂商</th>
                            <th>设备类型</th>
                            <th>制式</th>
                            <th>原网元名称</th>
                            <th>现网元名称</th>
                            <th>入库时间</th>
                            <th>出库时间</th>
                            <th>销库时间</th>
                            <th>状态</th>
                        </tr>
                    </thead>
                    <tbody id="equipmentList">
                        {% for item in equipment_list %}
                        <tr>
                            <td><input type="checkbox" class="equipment-checkbox" value="{{ item.sn }}"></td>
                            <td>{{ item.sn }}</td>
                            <td>{{ item.manufacturer }}</td>
                            <td>{{ item.type }}</td>
                            <td>{{ item.standard }}</td>
                            <td>{{ item.original_network_element }}</td>
                            <td>{{ item.current_network_element }}</td>
                            <td>{{ item.date.split('T')[0] + ' ' + item.date.split('T')[1] if 'T' in item.date else item.date }}</td>
                            <td>{{ item.outbound_time }}</td>
                            <td>{{ item.discard_time }}</td>
                            <td>
                                {% if item.status == '在库' %}
                                <span class="badge bg-success">在库</span>
                                {% elif item.status == '出库' %}
                                <span class="badge bg-warning">已出库</span>
                                {% elif item.status == '销库' %}
                                <span class="badge bg-danger">已销库</span>
                                {% else %}
                                <span class="badge bg-secondary">{{ item.status }}</span>
                                {% endif %}
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block scripts %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const searchForm = document.getElementById('searchForm');
    const exportBtn = document.getElementById('exportBtn');
    const deleteBtn = document.getElementById('deleteBtn');
    const equipmentList = document.getElementById('equipmentList');
    const selectAll = document.getElementById('selectAll');

    // 搜索功能
    searchForm.addEventListener('submit', function(e) {
        e.preventDefault();
        const formData = new FormData(searchForm);
        const params = new URLSearchParams(formData);

        fetch(`/search_inventory?${params.toString()}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    updateEquipmentList(data.equipment);
                } else {
                    alert('搜索失败：' + data.error);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('搜索过程中发生错误');
            });
    });

    // 导出功能
    exportBtn.addEventListener('click', function() {
        const formData = new FormData(searchForm);
        const params = new URLSearchParams(formData);
        window.location.href = `/export_inventory?${params.toString()}`;
    });

    // 更新设备列表
    function updateEquipmentList(equipment) {
        equipmentList.innerHTML = equipment.map(item => {
            const formattedDate = item.date.includes('T') ? 
                item.date.split('T')[0] + ' ' + item.date.split('T')[1] : 
                item.date;
            return `
                <tr>
                    <td><input type="checkbox" class="equipment-checkbox" value="${item.sn}"></td>
                    <td>${item.sn}</td>
                    <td>${item.manufacturer}</td>
                    <td>${item.type}</td>
                    <td>${item.standard}</td>
                    <td>${item.original_network_element}</td>
                    <td>${item.current_network_element}</td>
                    <td>${formattedDate}</td>
                    <td>${item.outbound_time}</td>
                    <td>${item.discard_time}</td>
                    <td>
                        ${item.status === '在库' ? 
                            '<span class="badge bg-success">在库</span>' : 
                            item.status === '出库' ? 
                                '<span class="badge bg-warning">已出库</span>' : 
                                item.status === '销库' ? 
                                    '<span class="badge bg-danger">已销库</span>' : 
                                    `<span class="badge bg-secondary">${item.status}</span>`
                        }
                    </td>
                </tr>
            `;
        }).join('');
    }

    // 全选/取消全选
    selectAll.addEventListener('change', function() {
        const checkboxes = document.querySelectorAll('.equipment-checkbox');
        checkboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
    });

    // 删除选中设备
    deleteBtn.addEventListener('click', function() {
        const checkboxes = document.querySelectorAll('.equipment-checkbox:checked');
        if (checkboxes.length === 0) {
            alert('请至少选择一条记录');
            return;
        }

        if (!confirm(`确定要删除选中的${checkboxes.length}条记录吗？`)) {
            return;
        }

        const snList = Array.from(checkboxes).map(checkbox => checkbox.value);
        
        fetch('/delete_inventory', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({sn_list: snList})
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert(`成功删除${data.count}条记录`);
                window.location.reload();
            } else {
                alert('删除失败：' + data.error);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('删除过程中发生错误');
        });
    });
});
</script>
{% endblock %}